# -*- coding:utf-8 -*-
import time

# @Time    : 2023/5/10 14:30
# @Author  : zengwenjia
# @Email   : zengwenjia@lingxi.ai
# @Software: LLM_internal

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

import requests
import json
from bot.chatgpt.chat_gpt_bot import ChatGPTBot
import config
from common.log import logger
import openai
import aiohttp
import asyncio
import itertools
import random
import uuid
from util_tool import utils
import os
import datetime
import threading
import settings

lock = threading.Lock()
try:
    loop = asyncio.get_event_loop()
except RuntimeError:
    asyncio.set_event_loop(asyncio.new_event_loop())
    loop = asyncio.get_event_loop()

class LLMAgentParent(object):
    def __init__(self, prompt, gpt_prompt_content=None):
        self.prompt = prompt
        self.gpt_prompt_content = gpt_prompt_content
        self.model_prompt = "你是一个专业的助手，你需要基于用户的问题，给出准确的答案。USER: " + self.prompt + " ASSISTANT:"

    def save_train_data(self, prompt, result, classname, file_name="llm", model_name="gpt-4", id=str(uuid.uuid1())):
        try:
            with lock:
                project_dir = os.path.dirname(os.path.dirname(__file__))
                # 带上日期的文件名yyyy-mm-dd
                now_date = datetime.datetime.now().strftime("%Y-%m-%d")
                now_datetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

                path = os.path.join(project_dir, "train_data/" + file_name + "/" + now_date + ".json")
                if not os.path.exists(path):
                    new_data = []
                else:
                    new_data = utils.jload(path)
                instruct_dict_new = {}
                instruct_dict_new["id"] = id
                instruct_dict_new["time"] = now_datetime
                instruct_dict_new["task"] = classname
                instruct_dict_new["model_name"] = model_name
                instruct_dict_new["conversations"] = []

                conversation_dict = {}
                conversation_dict["from"] = "human"
                conversation_dict["value"] = prompt
                instruct_dict_new["conversations"].append(conversation_dict)

                conversation_dict = {}
                conversation_dict["from"] = "gpt"
                conversation_dict["value"] = result
                instruct_dict_new["conversations"].append(conversation_dict)
                new_data.append(instruct_dict_new)
                utils.jdump(new_data, path)


        except Exception as ee:
            logger.error("save data error: {}".format(ee))
